name: PR Title Bot

on:
  issue_comment:
    types: [created]

jobs:
  handle_pr_title:
    runs-on: ubuntu-latest
    if: github.event.issue.pull_request && (contains(github.event.comment.body, '/suggest-title') || contains(github.event.comment.body, '/fix-title'))
    steps:
    - name: Checkout repository
      uses: actions/checkout@v3

    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: "3.10"

    - name: Install dependencies
      run: pip install pygithub openai tenacity

    - name: Get PR number
      id: get_pr_number
      run: |
        issue_url="${{ github.event.comment.issue_url }}"
        pr_number="${issue_url##*/}"
        echo "pr_number=$pr_number" >> $GITHUB_OUTPUT

    - name: Run script to get new title
      id: get_new_title
      run: |
        title=$(GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} OPENAI_API_KEY=${{ secrets.OPENAI_API_KEY }} python tools/pr-title-bot.py generate ${{ steps.get_pr_number.outputs.pr_number }})
        echo "title=$title" >> $GITHUB_OUTPUT

    - name: Suggest title
      if: contains(github.event.comment.body, '/suggest-title')
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        curl -L \
          -X POST \
          https://api.github.com/repos/${{ github.repository_owner }}/${{ github.event.repository.name }}/issues/${{ steps.get_pr_number.outputs.pr_number }}/comments \
          -H "Accept: application/vnd.github+json" \
          -H "Authorization: Bearer $GITHUB_TOKEN"\
          -H "X-GitHub-Api-Version: 2022-11-28" \
          --data '{ "body": "Suggested title:\n```\n${{ steps.get_new_title.outputs.title }}\n```" }'

    - name: Update PR title
      if: contains(github.event.comment.body, '/fix-title')
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        curl -L \
          -X POST \
          https://api.github.com/repos/${{ github.repository_owner }}/${{ github.event.repository.name }}/pulls/${{ steps.get_pr_number.outputs.pr_number }} \
          -H "Accept: application/vnd.github+json" \
          -H "Authorization: Bearer $GITHUB_TOKEN"\
          -H "X-GitHub-Api-Version: 2022-11-28" \
          --data '{ "title": "${{ steps.get_new_title.outputs.title }}" }'
